package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.constant.EsConstant;
import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.index.translog.Translog;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.Sum;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggester;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import sun.security.util.Length;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private RestHighLevelClient client;


    /**
     * 首页分页，并按照条件查询
     *
     * @param params
     * @return
     */
    @Override
    public PageResult<HotelDoc> getList(RequestParams params) {
        try {
            //1，准备request对象
            SearchRequest request = new SearchRequest(EsConstant.INDEX);
            //创建boolQuery对象
            buildBasicQuery(params, request);


            /*
             *//**
             *
             * 根据传到的经纬度，排序
             *//*
            String location = params.getLocation();

            request.source().sort(SortBuilders.
                    geoDistanceSort("location", new GeoPoint(location))
                    .order(SortOrder.ASC)
                    .unit(DistanceUnit.KILOMETERS));*/

            //分页查询条件
            int size = params.getSize();
            int page = params.getPage();
            //分页
            request.source().from((page - 1) * size)
                    .size(size);


            //发起请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //得到总数
            Long value = response.getHits().getTotalHits().value;

            SearchHit[] hits = response.getHits().getHits();

            List<HotelDoc> hotelDocs = new ArrayList<>();
            for (SearchHit hit : hits) {
                //得到每个文档数据的json数据
                String json = hit.getSourceAsString();
                //序列化为对象
                HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
                /**
                 * 给页面添加距离显示
                 */
                //获得排序数组
                Object[] sortValues = hit.getSortValues();
                int length = sortValues.length;
                if (length > 0) {
                    //最后一个数值是距离
                    Object sortValue = sortValues[length - 1];
                    //封装进返回的对象
                    hotelDoc.setDistance(sortValue);
                }
                //替换高亮数据，先获取高亮map集合
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (highlightFields != null && highlightFields.size() > 0) {
                    //通过键值，得到value值
                    HighlightField highlightField = highlightFields.get("name");
                    if (highlightField!=null) {
                        String name = highlightField.getFragments()[0].toString();
                        hotelDoc.setName(name);
                    }
                }
                hotelDocs.add(hotelDoc);
            }

            PageResult<HotelDoc> pageResult = new PageResult();
            pageResult.setHotels(hotelDocs);
            pageResult.setTotal(value);
            return pageResult;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new PageResult<HotelDoc>();
    }

    /**
     * 封装查询条件
     *
     * @param params
     * @param request
     */

    private void buildBasicQuery(RequestParams params, SearchRequest request) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();


        String key = params.getKey();
        //判断key是否为空
        if (key != null && !"".equals(key)) {
            //不为空的DSL，
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        } else {
            //为空的DSL
            boolQuery.must(QueryBuilders.matchAllQuery());
        }


        /**
         * 按照条件过滤酒店
         */
        //使用布尔查询。创建boolQuery对象
        String city = params.getCity();
        String starName = params.getStarName();
        String brand = params.getBrand();
        if (city != null && !"".equals(city)) {

            boolQuery.must(QueryBuilders.termQuery("city", city));
        }
        if (starName != null && !"".equals(starName)) {

            boolQuery.must(QueryBuilders.termQuery("starName", starName));
        }
        if (brand != null && !"".equals(brand)) {

            boolQuery.must(QueryBuilders.termQuery("brand", brand));
        }
        Integer minPrice = params.getMinPrice();
        Integer maxPrice = params.getMaxPrice();
        boolQuery.filter(QueryBuilders.rangeQuery("price").gte(minPrice).lte(maxPrice));

        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(boolQuery,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", "true"),
                                ScoreFunctionBuilders.weightFactorFunction(100)
                        )
                }
        ).boostMode(CombineFunction.SUM);
        //高亮查询
        request.source().query(functionScoreQueryBuilder)
                .highlighter(new HighlightBuilder()
                        .field("name")
                        .requireFieldMatch(false));
    }

    /**
     * @param params
     * @return
     */
    @Override
    public Map<String, List<String>> filters(RequestParams params) {
        try {
            //创建查询条件
            SearchRequest request = new SearchRequest("hotel");

            //过滤条件
            buildBasicQuery(params, request);


            //2.聚合
            //2.1 品牌聚合
            aggByName(request, "brandAgg", "brand", 10);
            //2.2 星级聚合
            aggByName(request, "starNameAgg", "starName", 10);
            //2.3 城市聚合
            aggByName(request, "cityAgg", "city", 10);

            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //3,处理结果
            Map<String, List<String>> resultMap = new HashMap<>();

            List<String> brandList = getListByAggName(response, "brandAgg");
            resultMap.put("brand", brandList);

            List<String> cityList = getListByAggName(response, "cityAgg");
            resultMap.put("city", cityList);

            List<String> starNameList = getListByAggName(response, "starNameAgg");
            resultMap.put("starName", starNameList);

            return resultMap;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new HashMap<>();
    }

    /**
     * 自动补全功能
     *
     * @param prefix
     * @return
     */
    @Override
    public List<String> getSuggestions(String prefix) {

        try {
            //1、准备SearchRequest
            SearchRequest request = new SearchRequest(EsConstant.INDEX);
            //2、准备DSL
            request.source().suggest(new SuggestBuilder().
                    addSuggestion("hotel_suggest",
                            SuggestBuilders.completionSuggestion("suggestion")
                                    .prefix(prefix)
                                    .size(10)
                                    .skipDuplicates(true))
            );
            //3、发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //4、解析结果,
            ArrayList<String> resultList = new ArrayList<>();
            //4.1直接获得suggest对象
            Suggest suggest = response.getSuggest();
            CompletionSuggestion completionSuggestion = suggest.getSuggestion("hotel_suggest");
            List<CompletionSuggestion.Entry.Option> options = completionSuggestion.getOptions();
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                resultList.add(text);
            }
            return resultList;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }

    /**
     * 根据集合名称获得结果集合
     *
     * @param response
     * @param aggName
     * @return
     */
    private List<String> getListByAggName(SearchResponse response, String aggName) {
        ArrayList<String> list = new ArrayList<>();
        Aggregations aggregations = response.getAggregations();
        Terms brandAgg = aggregations.get(aggName);
        List<? extends Terms.Bucket> buckets = brandAgg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            String keyAsString = bucket.getKeyAsString();
            list.add(keyAsString);
        }
        return list;
    }

    /**
     * 桶聚合条件
     *
     * @param request
     * @param aggName
     * @param fieldName
     * @param size
     */
    private void aggByName(SearchRequest request, String aggName, String fieldName, Integer size) {
        //桶聚合条件
        request.source()
                .size(0)
                .aggregation(AggregationBuilders
                        .terms(aggName)
                        .field(fieldName)
                        .size(size));
    }


}
